package main

import (
	"context"
	"fmt"
	"time"

	"go.etcd.io/etcd/api/v3/mvccpb"
	"go.etcd.io/etcd/client/v3"
)

// Watch
func main() {

	cfg := clientv3.Config{
		Endpoints: []string{"192.168.0.121:2379"},

		DialTimeout: 5 * time.Second,
	}

	client, err := clientv3.New(cfg)
	if err != nil {
		fmt.Println(err)
		return
	}

	kv := clientv3.NewKV(client)

	go func() {
		for true {
			kv.Put(context.TODO(), "/cron/job/job6", "job6")
			kv.Delete(context.TODO(), "/cron/job/job6")
			time.Sleep(2 * time.Second)
		}
	}()
	time.Sleep(time.Second)

	getResp, err := kv.Get(context.TODO(), "/cron/job/job6")
	if err != nil {
		fmt.Println(err)
		return
	}

	watcher := clientv3.NewWatcher(client)

	fmt.Println("开始监听版本：", getResp.Header.Revision+1)

	ctx, cancel := context.WithCancel(context.Background())
	time.AfterFunc(5*time.Second, func() {
		cancel()
	})

	watchCh := watcher.Watch(ctx, "/cron/job/job6", clientv3.WithRev(getResp.Header.Revision+1))

	for watchResp := range watchCh {
		for _, event := range watchResp.Events {
			switch event.Type {
			case mvccpb.PUT:
				fmt.Println("修改为：", string(event.Kv.Value), "Revision:", event.Kv.CreateRevision, event.Kv.ModRevision)
			case mvccpb.DELETE:
				fmt.Println("删除了：", "Revision:", event.Kv.ModRevision)
			}
		}

	}
	fmt.Println("退出监听...")

}
